package com.example.yangxu0703.thundermapclient.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.AMapNaviViewListener;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapModelCross;
import com.amap.api.navi.model.AMapNaviCameraInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AMapServiceAreaInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.example.yangxu0703.thundermapclient.R;
import com.example.yangxu0703.thundermapclient.activity.MainActivity;
import com.example.yangxu0703.thundermapclient.callback.StringResultCallback;
import com.thundersoft.mm.phone.ConnectionManager;

import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * A simple {@link Fragment} subclass.
 */
public class MapDirectionFragment extends Fragment implements AMapNaviListener, AMapNaviViewListener {
    private View view;
    private AMapNaviView aMapNaviView;
    private AMapNavi mAMapNavi;
    public EditText directtion;
    private Stack<String> message = new Stack<>();
    private boolean istrue = true;

    private NaviLatLng endLatlng = new NaviLatLng(RouteFragment.mEndPoint.getLatitude(), RouteFragment.mEndPoint.getLongitude());
    private NaviLatLng startLatlng = new NaviLatLng(RouteFragment.mStartPoint.getLatitude(), RouteFragment.mStartPoint.getLongitude());
    private List<NaviLatLng> startList = new ArrayList<NaviLatLng>();
    private RouteOverLay mRouteOverlay;
    /**
     * 定位API
     */
    /*public AMapLocationClient mlocationClient;
    public AMapLocationClientOption mLocationOption = null;
    public OnLocationChangedListener listener;*/


    private List<NaviLatLng> wayList = new ArrayList<NaviLatLng>();
    private List<NaviLatLng> endList = new ArrayList<NaviLatLng>();
    private int strategyFlag = 0;

    public StringResultCallback callback;

    public void setCallback(StringResultCallback callback) {
        this.callback = callback;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_blank, null, false);
        aMapNaviView = (AMapNaviView) view.findViewById(R.id.navi_view);
       // directtion = view.findViewById(R.id.name_end);
        aMapNaviView.onCreate(savedInstanceState);
        aMapNaviView.setAMapNaviViewListener(MapDirectionFragment.this);

        Log.i("tag", "oncreatview");
        initNavi();

     /*   IFlyTTS.getInstance(getActivity()).setCallback(new ICallBack() {
            @Override
            public void onCompleted(int code) {
                if (code == 0) {
                    if (message.size() != 0) {
                        IFlyTTS.getInstance(getActivity()).playText(message.pop());
                    }
                }
            }
        });*/
        return view;
    }


    private void calculateDriveRoute(int choose) {

        switch (choose) {
            case 1:
                //避免拥堵
                try {
                    strategyFlag = mAMapNavi.strategyConvert(true, false, false, false, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mAMapNavi.calculateDriveRoute(startList, endList, wayList, strategyFlag);
                break;
            case 2:
                //高速优先
                try {
                    strategyFlag = mAMapNavi.strategyConvert(false, false, false, true, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mAMapNavi.calculateDriveRoute(startList, endList, wayList, strategyFlag);
                break;
            case 3:
                //不走高速
                try {
                    strategyFlag = mAMapNavi.strategyConvert(false, true, false, false, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mAMapNavi.calculateDriveRoute(startList, endList, wayList, strategyFlag);
                break;
            case 4:
                //费用最少
                try {
                    strategyFlag = mAMapNavi.strategyConvert(false, false, true, false, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mAMapNavi.calculateDriveRoute(startList, endList, wayList, strategyFlag);
                break;
            case 5:
                mAMapNavi.calculateWalkRoute(startLatlng,endLatlng);
                break;
        }


    }

    private void initNavi() {
        Log.i("tag", "initNavi");
        startList.add(DirectinfoFragment.start_dir);
        endList.add(DirectinfoFragment.end_dir);
        mAMapNavi = AMapNavi.getInstance(getActivity());
        mAMapNavi.addAMapNaviListener(MapDirectionFragment.this);
    }

    private void cleanRouteOverlay() {
        if (mRouteOverlay != null) {
            mRouteOverlay.removeFromMap();
            mRouteOverlay.destroy();
        }
    }

    public void startNavi() {
        mAMapNavi.setEmulatorNaviSpeed(60);
        mAMapNavi.startNavi(AMapNavi.EmulatorNaviMode);
    }

    public void pauseNavi() {
        mAMapNavi.pauseNavi();
    }

    public void resumeNavi() {
        mAMapNavi.resumeNavi();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
        aMapNaviView.onResume();
        Log.i("tag", "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        aMapNaviView.onPause();
        mAMapNavi.stopNavi();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("tag", "destroy mapdirect!");
        if (mAMapNavi != null) {
            mAMapNavi.destroy();
        }
        if (aMapNaviView != null) {
            aMapNaviView.onDestroy();
        }

        //IFlyTTS.getInstance(getActivity()).stopSpeak();
    }

    @Override
    public void onNaviSetting() {

    }

    @Override
    public void onNaviCancel() {
        Log.i("NAV","onNaviCancel");
        calculateDriveRoute(MainActivity.choose);
        ((MainActivity)getActivity()).handler.sendEmptyMessage(4);
    }

    @Override
    public boolean onNaviBackClick() {
        return false;
    }

    @Override
    public void onNaviMapMode(int i) {

    }

    @Override
    public void onNaviTurnClick() {

    }

    @Override
    public void onNextRoadClick() {

    }

    @Override
    public void onScanViewButtonClick() {

    }

    @Override
    public void onLockMap(boolean b) {

    }

    @Override
    public void onNaviViewLoaded() {

    }

    @Override
    public void onInitNaviFailure() {
        Log.i("tag", "onInitNaviFailure");
    }

    @Override
    public void onInitNaviSuccess() {
        Log.i("tag", "onInitNaviSuccess");
        calculateDriveRoute(MainActivity.choose);

    }

    @Override
    public void onStartNavi(int i) {
        Log.i("tag", "onStartNavi");
    }

    @Override
    public void onTrafficStatusUpdate() {
        Log.i("tag", "onTrafficStatusUpdate");
    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {
        Log.i("tag", "onLocationChange");
    }

    @Override
    public void onGetNavigationText(int i, String s) {
        Log.i("onGetNavigationTexttag", s);
       /* if (istrue) {
            message.push(s);
            IFlyTTS.getInstance(getActivity()).playText(message.pop());
            istrue = false;
        } else {
            message.push(s);
        }*/
        // callback.stringcallback("Text" + "<>" + s);
    }

    @Override
    public void onGetNavigationText(String s) {
        Log.i("tag", "onGetNavigationText");
    }

    @Override
    public void onEndEmulatorNavi() {
        Log.i("tag", "onEndEmulatorNavi");
    }

    @Override
    public void onArriveDestination() {
        Log.i("tag", "onArriveDestination");
        //退出导航界面
        callback.stringcallback("Update" + "<>" +"");

    }

    @Override
    public void onCalculateRouteFailure(int i) {
        cleanRouteOverlay();
        //startNavi();
    }

    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {
        try {
            Log.i("DATA", naviInfo.toString());
            JSONObject body = new JSONObject();

            body.put("iconType", String.valueOf(naviInfo.getIconType()));
            //body.put("curStepRetainDistance", String.valueOf(naviInfo.getCurStepRetainDistance()));
            //body.put("currentRoadName", String.valueOf(naviInfo.getCurrentRoadName()));
            body.put("nextRoadName", String.valueOf(naviInfo.getNextRoadName()));
            body.put("pathRetainDistance", String.valueOf(naviInfo.getPathRetainDistance()));
            //body.put("pathRetainTime", String.valueOf(naviInfo.getPathRetainTime()));
            //ServerApi.sendNaviMessage(body);
            callback.stringcallback("Update" + "<>" + body.toString());
            Log.i("tts_0", body.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) {

    }

    @Override
    public void updateCameraInfo(AMapNaviCameraInfo[] aMapNaviCameraInfos) {

    }

    @Override
    public void onServiceAreaUpdate(AMapServiceAreaInfo[] aMapServiceAreaInfos) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showModeCross(AMapModelCross aMapModelCross) {

    }

    @Override
    public void hideModeCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateRouteSuccess(int[] ints) {
        Log.i("tag", "onCalculateRouteSuccess");
        //mAMapNavi.startNavi(NaviType.EMULATOR);
        startNavi();//计算路线成功后开启导航！
    }

    @Override
    public void notifyParallelRoad(int i) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {

    }

    @Override
    public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {

    }

    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {

    }

    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {

    }

    @Override
    public void onPlayRing(int i) {

    }
}
